﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace Corina.Interactivity.Silverlight
{
    public class DatePickerEnterKeyTrigger : TriggerBase<UIElement>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            DatePicker datepicker = this.AssociatedObject as DatePicker;

            if (datepicker != null)
            {
                this.AssociatedObject.KeyUp += new System.Windows.Input.KeyEventHandler(AssociatedObject_KeyUp);
            }
            else
            {
                throw new InvalidOperationException("This behavior only works with TextBoxes");
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.KeyUp -= new KeyEventHandler(AssociatedObject_KeyUp);
        }

        private void AssociatedObject_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                DatePicker datepicker = AssociatedObject as DatePicker;

                //This checks for an mvvm style binding and updates the source before invoking the actions.
                BindingExpression expression = datepicker.GetBindingExpression(DatePicker.SelectedDateProperty);
                if (expression != null)
                    expression.UpdateSource();

                InvokeActions(datepicker.SelectedDate);
            }
        }
    }
}
